package com.example.imitation_webchat_demo.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.imitation_webchat_demo.R;
import com.example.imitation_webchat_demo.adapter.ChatMsgViewAdapter;
import com.example.imitation_webchat_demo.adapter.FaceGVAdapter;
import com.example.imitation_webchat_demo.adapter.FaceVPAdapter;
import com.example.imitation_webchat_demo.entity.ChatMsgEntity;
import com.example.imitation_webchat_demo.util.AppUtils;
import com.example.imitation_webchat_demo.util.ApplicationUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

// 聊天activity
public class ChatActivity extends Activity {
	@ViewInject(R.id.chat_header_back)
	private Button backBtn;

	@ViewInject(R.id.chat_send_message)
	private EditText messageText;

	@ViewInject(R.id.chat_btn_send)
	private Button sendBtn;

	@ViewInject(R.id.chat_listview) 
	private ListView listView;

	// 表情图标
	@ViewInject(R.id.chat_image_face)
	private ImageView faceView;

	// 表情布局
	@ViewInject(R.id.chat_face_container)
	private LinearLayout chat_face_container;

	@ViewInject(R.id.face_viewpager)
	private ViewPager viewPager;

	// 表情下小圆点
	@ViewInject(R.id.face_dots_container)
	private LinearLayout dotsLayout;
	
	@ViewInject(R.id.chat_head_title)
	private TextView titleView;

	private List<View> views;

	private String message;
	private ChatMsgViewAdapter adapter;
	private List<ChatMsgEntity> list;
	private List<String> staticFacesList;

	// 表情页是6列4行
	private int columns = 6;
	private int rows = 4; 

	private final static int COUNT = 12;      // 初始化数组总数
	private String[] msgArray = new String[] { "有大吗", "有！你呢？", "我也有", "那上吧",
			"打啊！你放大啊！", "你TM咋不放大呢？留大抢人头啊？CAO！你个傻B", "2B不解释", "尼滚...",
			"今晚去网吧包夜吧？", "玩游戏不？", "玩呀~还怕没人？", "OK,搞起！！" };

	private String[] dataArray = new String[] { "2012-09-22 18:00:02",
			"2012-09-22 18:10:22", "2012-09-22 18:11:24",
			"2012-09-22 18:20:23", "2012-09-22 18:30:31",
			"2012-09-22 18:35:37", "2012-09-22 18:40:13",
			"2012-09-22 18:50:26", "2012-09-22 18:52:57",
			"2012-09-22 18:55:11", "2012-09-22 18:56:45",
			"2012-09-22 18:57:33", };
	
	private String username;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_chat_room);
		
		ViewUtils.inject(this);
		initComponent();         // 初始化控件
		getIntentData();         // 得到intent传过来的值
		
		ApplicationUtils.getInstance().addActivity(this);
	}

	// 初始化控件
	public void initComponent() {
		list = new ArrayList<ChatMsgEntity>();
		views = new ArrayList<View>();
		ChatMsgEntity entity = null;
		for (int i = 0; i < COUNT; i++) {
			entity = new ChatMsgEntity();
			entity.setTime(dataArray[i]);
			if (i % 2 == 0) {
				entity.setUsername("肖某某");
				entity.setComeMsg(true);        // 收到的消息
			} else {
				entity.setUsername("张某某");
				entity.setComeMsg(false);      // 自己发送的消息
			}
			entity.setMessage(msgArray[i]);
			list.add(entity);
		}
		adapter = new ChatMsgViewAdapter(this, list);
		listView.setAdapter(adapter);
		listView.setSelection(adapter.getCount() - 1);

		initStaticFaces();    // 初始化表情集
		initViewPager();      // 初始化ViewPager
		viewPager.setOnPageChangeListener(new PageChange());
		
		username = AppUtils.getUsernameFromShare(this);
	}
	
	public void getIntentData(){
		String username = getIntent().getStringExtra("username");
		titleView.setText("和 " + username + " 聊天中");
	}

	/**
	 * 初始化表情列表staticFacesList
	 */
	private void initStaticFaces() {
		try {
			staticFacesList = new ArrayList<String>();
			String[] faces = getAssets().list("face/png");
			// 将Assets中的表情名称转为字符串一一添加进staticFacesList
			for (int i = 0; i < faces.length; i++) {
				staticFacesList.add(faces[i]);
			}
			// 去掉删除图片
			staticFacesList.remove("emotion_del_normal.png");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//初始化ViewPager
	public void initViewPager() {
		// 获取页数
		for (int i = 0; i < getPagerCount(); i++) {
			views.add(viewPagerItem(i));
			LayoutParams params = new LayoutParams(16, 16);
			dotsLayout.addView(dotsItem(i), params);
		}
		FaceVPAdapter mVpAdapter = new FaceVPAdapter(views);
		viewPager.setAdapter(mVpAdapter);
		dotsLayout.getChildAt(0).setSelected(true);
	}

	private ImageView dotsItem(int position) {
		LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.dot_image, null);
		ImageView iv = (ImageView) layout.findViewById(R.id.face_dot);
		iv.setId(position);
		return iv;
	}

	/**
	 * 根据表情数量以及GridView设置的行数和列数计算Pager数量
	 * 
	 * @return
	 */
	private int getPagerCount() {
		int count = staticFacesList.size();
		return count % (columns * rows - 1) == 0 ? count / (columns * rows - 1)
				: count / (columns * rows - 1) + 1;
	}

	// 获取第position页的表情集所对应的View
	private View viewPagerItem(int position) {
		LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.face_gridview, null); // 表情布局
		GridView gridview = (GridView) layout.findViewById(R.id.chat_face_gv);
		/**
		 * 注：因为每一页末尾都有一个删除图标，所以每一页的实际表情columns*rows-1; 空出最后一个位置给删除图标
		 * */
		List<String> subList = new ArrayList<String>();
		subList.addAll(staticFacesList
				.subList(position * (columns * rows - 1),
						(columns * rows - 1) * (position + 1) > staticFacesList
								.size() ? staticFacesList.size() : (columns
								* rows - 1)
								* (position + 1)));
		/**
		 * 末尾添加删除图标
		 * */
		subList.add("emotion_del_normal.png");
		FaceGVAdapter mGvAdapter = new FaceGVAdapter(subList,
				this);
		gridview.setAdapter(mGvAdapter);
		gridview.setNumColumns(columns);
		
		// 单击表情执行的操作
		gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					String png = ((TextView) ((LinearLayout) view)
							.getChildAt(1)).getText().toString();
					if (!png.contains("emotion_del_normal")) {       // 如果不是删除图标
						insert(getFace(png));
					} else {
						delete();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		return gridview;
	}

	/**
	 * 向输入框里添加表情
	 * */
	private void insert(CharSequence text) {
		int iCursorStart = Selection.getSelectionStart((messageText.getText()));
		int iCursorEnd = Selection.getSelectionEnd((messageText.getText()));
		if (iCursorStart != iCursorEnd) {
			((Editable) messageText.getText()).replace(iCursorStart,
					iCursorEnd, "");
		}
		int iCursor = Selection.getSelectionEnd((messageText.getText()));
		((Editable) messageText.getText()).insert(iCursor, text);
	}

	/**
	 * 删除图标执行事件
	 * 注：如果删除的是表情，在删除时实际删除的是tempText即图片占位的字符串，所以必需一次性删除掉tempText，才能将图片删除
	 * */
	private void delete() {
		if (messageText.getText().length() != 0) {
			int iCursorEnd = Selection.getSelectionEnd(messageText.getText());
			int iCursorStart = Selection.getSelectionStart(messageText
					.getText());
			if (iCursorEnd > 0) {
				if (iCursorEnd == iCursorStart) {
					if (isDeletePng(iCursorEnd)) {
						String st = "#[face/png/f_static_000.png]#";
						((Editable) messageText.getText()).delete(iCursorEnd
								- st.length(), iCursorEnd);
					} else {
						((Editable) messageText.getText()).delete(
								iCursorEnd - 1, iCursorEnd);
					}
				} else {
					((Editable) messageText.getText()).delete(iCursorStart,
							iCursorEnd);
					
					Log.v("TAG", "不相等");
					
				}
			}
		}
	}

	/**
	 * 判断即将删除的字符串是否是图片占位字符串tempText 如果是：则讲删除整个tempText
	 * **/
	private boolean isDeletePng(int cursor) {
		String st = "#[face/png/f_static_000.png]#";
		String content = messageText.getText().toString().substring(0, cursor);
		if (content.length() >= st.length()) {
			String checkStr = content.substring(content.length() - st.length(),
					content.length());
			String regex = "(\\#\\[face/png/f_static_)\\d{3}(.png\\]\\#)";
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(checkStr);
			return m.matches();
		}
		return false;
	}

	private SpannableStringBuilder getFace(String png) {
		SpannableStringBuilder sb = new SpannableStringBuilder();
		try {
			/**
			 * 经过测试，虽然这里tempText被替换为png显示，但是但我单击发送按钮时，获取到輸入框的内容是tempText的值而不是png
			 * 所以这里对这个tempText值做特殊处理
			 * 格式：#[face/png/f_static_000.png]#，以方便判斷當前圖片是哪一個
			 * */
			String tempText = "#[" + png + "]#";
			sb.append(tempText);
			sb.setSpan(
					new ImageSpan(this, BitmapFactory
							.decodeStream(getAssets().open(png))),
					sb.length() - tempText.length(), sb.length(),
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb;
	}

	// 点击返回按钮响应
	@OnClick(R.id.chat_header_back)
	public void back(View view) {
		if(chat_face_container.getVisibility()==View.VISIBLE){
			chat_face_container.setVisibility(View.GONE);
		}else{
			finish();
		}
	}

	// 点击表情按钮
	@OnClick(R.id.chat_image_face)
	public void clickFace(View view) {
		hideSoftInputView();//隐藏软键盘
		if(chat_face_container.getVisibility() == View.GONE){
			chat_face_container.setVisibility(View.VISIBLE);
		}else{
			chat_face_container.setVisibility(View.GONE);
		}
	}

	/**
	 * 表情页改变时，dots效果也要跟着改变
	 * */
	class PageChange implements OnPageChangeListener {
		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			
		}

		@Override
		public void onPageSelected(int arg0) {
			for (int i = 0; i < dotsLayout.getChildCount(); i++) {
				dotsLayout.getChildAt(i).setSelected(false);
			}
			dotsLayout.getChildAt(arg0).setSelected(true);
		}
	}

	// 点击发送按钮
	@OnClick(R.id.chat_btn_send)
	public void sendMessage(View view) {
		message = messageText.getText().toString();

		if (message.length() > 0) {
			ChatMsgEntity entity = new ChatMsgEntity();
			entity.setUsername("张某某");
			entity.setTime(AppUtils.getFormatDateMsg("yyyy-MM-dd HH:mm:ss", new Date()));
			entity.setMessage(message);
			entity.setComeMsg(false);

			list.add(entity);

			adapter.notifyDataSetChanged();// 通知ListView，数据已发生改变
			messageText.setText("");// 清空编辑框数据
			listView.setSelection(listView.getCount() - 1);// 发送一条消息时，ListView显示选择最后一项
		}
	}

	// 隐藏软键盘
	public void hideSoftInputView() {
		InputMethodManager manager = ((InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE));
		if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
			if (getCurrentFocus() != null)
				manager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	@Override
	public void onBackPressed() {
		if(chat_face_container.getVisibility()== View.VISIBLE){
			chat_face_container.setVisibility(View.GONE);
		}else{
			super.onBackPressed();
		}
	}

	@Override
	protected void onDestroy() {
		ApplicationUtils.getInstance().removeActivity(this);
		super.onDestroy();
	}
}